package com.itheima.pay.controller;

import com.itheima.pay.entity.Result;
import com.itheima.pay.service.WxPayService;
import com.itheima.pay.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private WxPayService wxPayService;

    /**
     * 请求统一下单接口
     *
     * @return
     */
    @RequestMapping("/createNative")
    public Map createNative() {
        IdWorker idWorker = new IdWorker();
        return wxPayService.createNative(String.valueOf(idWorker.nextId()), "1");

    }

    /**
     * 查询订单接口
     *
     * @param out_trade_no
     * @return
     */
    @RequestMapping("/queryOrderStatus")
    public Result queryOrderStatus(String out_trade_no, HttpServletRequest request) {
        Result result = null;
        int x = 0;
        while (true) {

            Map map = wxPayService.queryOrderStatus(out_trade_no);
            if (map == null) {
                result = new Result(false, "查询发生错误！");
                break;
            }
            // 判断交易状态
            if ("SUCCESS".equals(map.get("trade_state"))) {
                result = new Result(true, "支付成功");
                // 实际过程中会去修改订单状态，此处省略
                break;
            }
            System.out.println("调用查询：" + map);

            try {
                Thread.sleep(3000);// 间隔三秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            x++;

            if (x >= 100) {
                result = new Result(false, "二维码超时");
                break;
            }

        }

        return result;
    }

}
